package fuzion24.device.vulnerability.vulnerabilities.helper;

import android.content.Context;
import android.os.Build;

import java.io.File;
import java.io.IOException;

import static fuzion24.device.vulnerability.vulnerabilities.helper.BinaryAssets.extractAsset;

public class CrashCheck {

    public static TestResult execute(Context context, int timeoutSeconds, String... cmdLine) throws IOException, InterruptedException {
        String crashCheckPath = extractCrashCheckBinary(context);

        String[] crashCheck = new String[cmdLine.length + 2];
        crashCheck[0] = crashCheckPath;
        crashCheck[1] = String.valueOf(timeoutSeconds);
        for (int i = 0; i < cmdLine.length; i++) {
            crashCheck[i + 2] = cmdLine[i];
        }

        Process process = Runtime.getRuntime().exec(crashCheck);
        int result = process.waitFor();

        switch (result) {
            case 254: return TestResult.CRASH;
            case 253: return TestResult.HANG;
            case 255: return TestResult.ERROR;
            default:  return TestResult.OK(result);
        }
    }

    private static String extractCrashCheckBinary(Context context) throws IOException {
        File dataDir = context.getFilesDir();
        String extractedCrashCheck = dataDir.getAbsolutePath() + File.separator + getCrashCheckAppName();
        extractAsset(context, "crashCheck" + File.separator + getCrashCheckAppName(), extractedCrashCheck, false);
        Process p = Runtime.getRuntime().exec("chmod 700 " + extractedCrashCheck);

        try {
            p.waitFor();
        }catch(Exception e){
            //
        }

        return extractedCrashCheck;
    }

    public static String getCrashCheckAppName() {
        return Build.VERSION.SDK_INT >= 16 ? "crashCheck-pie" : "crashCheck";
    }
}
